package com.kun.single_nacos;

import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingFactory;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.listener.Event;
import com.alibaba.nacos.api.naming.listener.EventListener;
import com.alibaba.nacos.api.naming.listener.NamingEvent;
import com.alibaba.nacos.api.naming.pojo.Instance;

import java.io.IOException;
import java.util.List;
import java.util.Properties;


/**
 * 服务注册
 * */
public class ServiceRegister {

    public static void main(String[] args) throws NacosException, IOException {
        Properties properties = new Properties();
        // 设置nacos服务地址
        properties.setProperty("serverAddr", "192.168.2.183:8848");

        // 构建NamingService对象
        NamingService naming = NamingFactory.createNamingService(properties);

        // 服务注册，注册两个实例上去
        naming.registerInstance("my-service", "192.168.0.101", 8881, "CLUSTER1");
        naming.registerInstance("my-service", "192.168.0.102", 8882, "CLUSTER2");

        // 获取服务实例列表
        List<Instance> instances = naming.getAllInstances("my-service");
        System.out.println("实例数：" + instances.size());

        // 获取一个健康实例（随机策略）
        Instance instance = naming.selectOneHealthyInstance("my-service");
        System.out.println("服务实例:" + instance.getClusterName() + "；IP:" + instance.getIp() + "；端口:" + instance.getPort());

        // 服务订阅
        naming.subscribe("my-service", new EventListener() {
            @Override
            public void onEvent(Event event) {
                NamingEvent namingEvent = (NamingEvent) event;
                // 获取到服务实例列表
                List<Instance> instanceList = namingEvent.getInstances();
                // 打印输出
                StringBuilder sb = new StringBuilder();
                for (Instance instance : instanceList) {
                    sb.append("\n").append(instance);
                }
            }
        });

        // 防止主线程退出，便于观察订阅的打印输出
        int in = System.in.read();
    }
}
